package org.csu.mypetstore.controller;

import jakarta.servlet.http.HttpSession;
import jakarta.websocket.Session;
import org.csu.mypetstore.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@Controller
@RequestMapping("/Log")
public class LogController {
    @Autowired
    private LogService logService;

    @GetMapping("/log")
    public String getLog(Model model, HttpSession session) {
        // 校验用户是否登录
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return "redirect:/account/signonForm"; // 跳转到登录页
        }
        model.addAttribute("username", username);
        return "account/LogForm";
    }

    @PostMapping("/log")
    @ResponseBody  // 直接返回 JSON 数据
    public Map<String, Object> log(
            @RequestParam String logInfo,
            HttpSession session
    ) {
        Map<String, Object> response = new HashMap<>();
        String username = (String) session.getAttribute("username");

        if (username == null) {
            response.put("status", "error");
            response.put("message", "用户未登录");
            return response;
        }

        try {
            logService.insertLogInfo(username, logInfo);
            response.put("status", "success");
            response.put("message", "日志提交成功");
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "服务器错误：" + e.getMessage());
        }
        return response;
    }
}
